<script lang="ts" setup>
import type { VxeTableGridOptions } from '#/adapter/vxe-table';
import type { EdubaseSchoolTeachingUnitApi } from '#/api/edu/base/schoolTeachingUnit';

import { nextTick, ref } from 'vue';

import { confirm, Page, useVbenModal } from '@vben/common-ui';
import { downloadFileFromBlobPart, isEmpty } from '@vben/utils';

import { message } from 'ant-design-vue';

import { ACTION_ICON, TableAction, useVbenVxeGrid } from '#/adapter/vxe-table';
import {
  checkOrg,
  deleteSchoolTeachingUnit,
  deleteSchoolTeachingUnitList,
  exportSchoolTeachingUnit,
  getSchoolTeachingUnitPage,
} from '#/api/edu/base/schoolTeachingUnit';
import { $t } from '#/locales';

import { useGridColumns, useGridFormSchema } from './data';
import Detail from './modules/detail.vue';
import Form from './modules/form.vue';

const orgInfo = ref<EdubaseSchoolTeachingUnitApi.EduOrgCheckVO>({
  showCampus: false,
  showCollege: false,
  showDepartment: false,
  showFaculty: false,
  showGroup: false,
});
async function getOrg() {
  const data = await checkOrg();
  let orgInfoData = {} as EdubaseSchoolTeachingUnitApi.EduOrgCheckVO;
  if (data) {
    if (data.isSchool) {
      if (data.showCampus) {
        orgInfoData.campusDictList = data.children || [];
      }
      if (data.showCollege) {
        orgInfoData.collegeDictList = data.children || [];
      }
      if (data.showDepartment) {
        orgInfoData.departmentDictList = data.children || [];
      }
      if (data.showFaculty) {
        orgInfoData.facultyDictList = data.children || [];
      }
      if (data.showGroup) {
        orgInfoData.groupDictList = data.children || [];
      }
      orgInfoData.isSchool = data.isSchool;
      orgInfoData.showCampus = data.showCampus;
      orgInfoData.showCollege = data.showCollege;
      orgInfoData.showDepartment = data.showDepartment;
      orgInfoData.showFaculty = data.showFaculty;
      orgInfoData.showGroup = data.showGroup;
    } else {
      orgInfoData = {
        showCampus: false,
        showCollege: false,
        showDepartment: false,
        showFaculty: false,
        showGroup: false,
        isSchool: false,
      };
    }
  } else {
    orgInfoData = {
      showCampus: false,
      showCollege: false,
      showDepartment: false,
      showFaculty: false,
      showGroup: false,
      isSchool: false,
    };
  }
  orgInfo.value = orgInfoData;
  nextTick().then(() => {
    gridApi.formApi?.setValues({
      ...orgInfoData,
      orgType: '110106',
      distabledOrgType: true,
    });
  });
}
getOrg();
const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});

const [DetailModal, detailModalApi] = useVbenModal({
  connectedComponent: Detail,
  destroyOnClose: true,
});
const desensitize = ref<boolean>(true); // 是否脱敏
function handleDesensitize() {
  desensitize.value = !desensitize.value;
  gridApi.reload();
}
/** 刷新表格 */
function handleRefresh() {
  gridApi.reload();
}

/** 创建教学单位表（院、系、学部、组） */
function handleCreate() {
  formModalApi
    .setData({ ...orgInfo.value, orgType: '110106', distabledOrgType: true })
    .open();
}

/** 编辑教学单位表（院、系、学部、组） */
function handleEdit(row: EdubaseSchoolTeachingUnitApi.SchoolTeachingUnit) {
  formModalApi
    .setData({ ...row, ...orgInfo.value, distabledOrgType: true })
    .open();
}

/** 查看教学单位表（院、系、学部、组） */
function handleDetail(row: EdubaseSchoolTeachingUnitApi.SchoolTeachingUnit) {
  detailModalApi.setData({ ...row, distabledOrgType: true }).open();
}

/** 删除教学单位表（院、系、学部、组） */
async function handleDelete(
  row: EdubaseSchoolTeachingUnitApi.SchoolTeachingUnit,
) {
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deleting', [row.id]),
    duration: 0,
  });
  try {
    await deleteSchoolTeachingUnit(row.id as number);
    message.success({
      content: $t('ui.actionMessage.deleteSuccess', [row.id]),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

/** 批量删除教学单位表（院、系、学部、组） */
async function handleDeleteBatch() {
  await confirm($t('ui.actionMessage.deleteBatchConfirm'));
  const hideLoading = message.loading({
    content: $t('ui.actionMessage.deletingBatch'),
    duration: 0,
  });
  try {
    await deleteSchoolTeachingUnitList(checkedIds.value);
    checkedIds.value = [];
    message.success({
      content: $t('ui.actionMessage.deleteSuccess'),
    });
    handleRefresh();
  } finally {
    hideLoading();
  }
}

const checkedIds = ref<number[]>([]);
function handleRowCheckboxChange({
  records,
}: {
  records: EdubaseSchoolTeachingUnitApi.SchoolTeachingUnit[];
}) {
  checkedIds.value = records.map((item) => item.id!);
}

/** 导出表格 */
async function handleExport() {
  const data = await exportSchoolTeachingUnit(
    await gridApi.formApi.getValues(),
  );
  downloadFileFromBlobPart({
    fileName: '系信息.xls',
    source: data,
  });
}

const [Grid, gridApi] = useVbenVxeGrid({
  formOptions: {
    schema: useGridFormSchema(),
  },
  gridOptions: {
    id: 'SchoolTeachingUnit-grid',
    columns: useGridColumns(),
    height: 'auto',
    pagerConfig: {
      enabled: true,
    },
    keepSource: true,
    proxyConfig: {
      ajax: {
        query: async ({ page }, formValues) => {
          return await getSchoolTeachingUnitPage(
            {
              pageNo: page.currentPage,
              pageSize: page.pageSize,
              ...formValues,
              orgType: '110106',
            },
            desensitize.value,
            false,
          );
        },
      },
    },
    rowConfig: {
      keyField: 'id',
      isHover: true,
    },
    toolbarConfig: {
      refresh: true,
      search: true,
    },
  } as VxeTableGridOptions<EdubaseSchoolTeachingUnitApi.SchoolTeachingUnit>,
  gridEvents: {
    checkboxAll: handleRowCheckboxChange,
    checkboxChange: handleRowCheckboxChange,
  },
});
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="handleRefresh" />
    <DetailModal @success="handleRefresh" />
    <Grid table-title="系列表">
      <template #toolbar-tools>
        <TableAction
          :actions="[
            {
              label: desensitize ? '关闭脱敏' : '启用脱敏',
              type: 'primary',
              danger: desensitize,
              icon: desensitize
                ? 'ant-design:eye-filled'
                : 'ant-design:eye-invisible-filled',
              auth: ['edu:base:admin-department:query'],
              onClick: handleDesensitize,
            },
            {
              label: $t('ui.actionTitle.create', ['系']),
              type: 'primary',
              icon: ACTION_ICON.ADD,
              auth: ['edu:base:school-teaching-unit:create'],
              onClick: handleCreate,
            },
            {
              label: $t('ui.actionTitle.export'),
              type: 'primary',
              icon: ACTION_ICON.DOWNLOAD,
              auth: ['edu:base:school-teaching-unit:export'],
              onClick: handleExport,
            },
            {
              label: $t('ui.actionTitle.deleteBatch'),
              type: 'primary',
              danger: true,
              icon: ACTION_ICON.DELETE,
              disabled: isEmpty(checkedIds),
              auth: ['edu:base:school-teaching-unit:delete'],
              onClick: handleDeleteBatch,
            },
          ]"
        />
      </template>

      <template #actions="{ row }">
        <TableAction
          :actions="[
            {
              label: '查看',
              type: 'link',
              icon: ACTION_ICON.VIEW,
              auth: ['edu:base:school-teaching-unit:query'],
              onClick: handleDetail.bind(null, row),
            },
            {
              label: $t('common.edit'),
              type: 'link',
              icon: ACTION_ICON.EDIT,
              auth: ['edu:base:school-teaching-unit:update'],
              onClick: handleEdit.bind(null, row),
            },
            {
              label: $t('common.delete'),
              type: 'link',
              danger: true,
              icon: ACTION_ICON.DELETE,
              auth: ['edu:base:school-teaching-unit:delete'],
              popConfirm: {
                title: $t('ui.actionMessage.deleteConfirm', [row.name]),
                confirm: handleDelete.bind(null, row),
              },
            },
          ]"
        />
      </template>
    </Grid>
  </Page>
</template>
